<?php

class GameLoginAction extends SzAbstractAction
{
    protected $paramTypes = array(
        SzAbstractAction::TYPE_STRING
    );

    /**
     *  登录
     *
     * @param int $platformId 平台id eg. sdk_id, fb_id
     * @param string $platform 平台 eg. SzSdk, facebook
     * @param int $gameId 数据通道game_id
     * @param int $cpGameId sdk中心game_id
     * @param string $deviceId 设备id
     * @param string $token SzSdk token
     * @param array $platformInfo 第三方平台信息 eg. {fb_id:11, ...}
     * @return SzResponse
     * @throws SzException
     */
    public function execute(
        $platformId,
        $platform = 'dev',
        $gameId = 71,
        $cpGameId = 1071,
        $deviceId = 'dev',
        $platformInfo = array(),
        $token = '',
        $param = ''
    )
    {
        if (!$platformId or $platformId == "null" or $platformId == "false" or $platformId == '') {
            throw new SzException(20004, array($platformId));
        }

        $anonymousId = null;

        // 判断是否是开发参数 demo: dev_r-nhFzDBJYbcMSdP
        $dev = false;
        if (strpos($platform, '_') != false) {
            $temp = explode('_', $platform);
            $platform = $temp[1];
            $dev = true;
        } else {
            $anonymousId = SzParam::getReqParam('anonymousId', null);
        }

        if (isset($anonymousId) and $anonymousId == 'null') $anonymousId = null;

        // 判断是否是机器人登录
        $appConfig = SzConfig::get()->loadAppConfig('app');
        $connPlatformId = ($anonymousId and $anonymousId != $platformId) ? $anonymousId : $platformId;
        if ($platformId == 'robot001' && $appConfig['ABLE_ROBOT_LOGIN'] == true) {
            // 机器人登录，跳过验证
        } else {
            if ($dev) {
                $loginName = 'dev';
            } else {
                $loginName = $platform;
            }

            // 验证token
            if (!PlatformService::get()->checkToken($loginName, $connPlatformId, $token)) {
                throw new SzException(20046, 'platform error, request platform: ' . $platform);
            }
        }

        // 新用户首次登录将初始化游戏相关数据
        $zoneid = $_REQUEST['zoneid'] ?? '';
        if ($platform == 'qq') {
            $platformInfo = [$platform => $platformId . intval($zoneid)];
            $oldPlatformInfo = [$platform => $anonymousId . intval($zoneid)];
        } else {
            $platformInfo = [$platform => $platformId . $zoneid];
            $oldPlatformInfo = [$platform => $anonymousId . $zoneid];
        }

        // 获取用户id
        if ($anonymousId and $anonymousId != $platformId) {
            list($userId, $platformInfo) = PlatformService::get()->newPortPlayerUserId($platformInfo, $oldPlatformInfo);
        } else {
            list($userId, $platformInfo) = PlatformService::get()->portPlayerUserId($platformInfo, true);
        }

        // 设置用户id
        SzSystem::handleIdentify(null, $userId);

        // 封号用户检测
        if ($platform == 'H5WeChat') {
            if (in_array($userId, GameConst::GAME_CHEATING_USERS_WEIXIN)) {
                echo '危险账号，禁止入内!!';
                die();
            }
        }
        if ($platform == 'wanba') {
            if (in_array($userId, GameConst::GAME_CHEATING_USERS_WANBA)) {
                echo '危险账号，禁止入内!!';
                die();
            }
        }
        if ($platform == 'qq') {
            if (in_array($userId, GameConst::GAME_CHEATING_USERS_QQSG)) {
                echo '危险账号，禁止入内!!';
                die();
            }
        }
        if ($platform == 'oppo') {
            if (in_array($userId, GameConst::GAME_CHEATING_USERS_OPPO)) {
                echo '危险账号，禁止入内!!';
                die();
            }
        }
        if ($platform == 'dev') {
            if (in_array($userId, GameConst::GAME_CHEATING_USERS_DEV)) {
                echo '危险账号，禁止入内!!';
                die();
            }
        }

        // 创建机器人uid
        if ($platformId == 'robot001') {
            if (!GameService::get()->getGlobalValue(GameConst::GLOBAL_INFO_TYPE_ID_ROBOT_FRIEND)) {
                GameService::get()->updateGlobalValue(GameConst::GLOBAL_INFO_TYPE_ID_ROBOT_FRIEND, $userId);
            }
        }

        // 获取玩家数据，如果玩家不存在，则创建
        $profile = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        $IS_INSTALL = false;
        if (!$profile) {
            GameService::get()->createPlayerGameData($userId, $platformId, $platform, $platformInfo);
            $IS_INSTALL = true;
        } else {
            UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM, $platform);
            UserService::get()->updatePlatformInfo($userId, $platformInfo);
        }
        UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM_TOKEN, $token);

        // 清空网络序号包
        SzContextFactory::get()->getStaticCache($userId)->delete(GameConst::CACHE_KEY_PKG_INDEX . $userId);

        // 判断是否为同一设备登陆
        $oldToken = SzContextFactory::get()->getStaticCache($userId)->get(GameConst::CACHE_KEY_TOKEN . $userId);
        if (!$oldToken || !GameService::get()->verifyIsSameDevice($userId, $deviceId)) {
            $token = GameService::get()->initSessionToken($userId);
            if ('dev' != $deviceId && '' != $deviceId) {
                SzContextFactory::get()->getStaticCache($userId)->set(GameConst::CACHE_KEY_USER_DEVICE_ID . $userId, $deviceId, SzTime::MINUTE * 5);
            }
        } else {
            $token = $oldToken;
            SzContextFactory::get()->getStaticCache($userId)->expire(GameConst::CACHE_KEY_TOKEN . $userId, SzTime::HOURS24);
        }

        if ($IS_INSTALL) {
            // 数据采集：设备激活
            if ($deviceId == 'dev') {
                $deviceId = '';
            }
            $data = array(
                'clientData' => array(
                    'tid' => '',
                    'item' => '',
                    'value' => 3,
                )
            );

            if ($param != '') {
                $data = array(
                    'clientData' => array(
                        'tid' => 'channel:' . $param,
                        'item' => 'channel_source',
                        'value' => 3,
                    )
                );
            }

            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_INSTALL, $data, null, null, $deviceId);
        }
        $isInitPlatform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM_INFO);
        //栅栏数据清理
        GameService::get()->deleteFenceData($userId);
        // 数据采集：登陆加载
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_VISIT, array(
            'clientData' => array(
                'tid' => '',
                'item' => '',
                'value' => 1,
            )
        ));

        //        // 数据采集：登陆加载
        //        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_LOAD_STEP, array(
        //            'clientData' => array(
        //                'tid' => '',
        //                'item' => 'flash_load_start'
        //            )
        //        ));
        //
        //        // 数据采集：登陆加载
        //        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_LOAD_STEP, array(
        //            'clientData' => array(
        //                'tid' => '',
        //                'item' => 'flash_load_end'
        //            )
        //        ));
        return $this->buildResponse(array(
            'WEB_HOST' => $appConfig['WEB_HOST'],
            'CDN_HOST' => $appConfig['CDN_HOST'],
            'USER_ID' => $userId,
            'TOKEN' => $token,
            'LANG' => GameService::get()->getLang($userId),
            //FIXME 等用户的 AB 版本区分后，这里写一个方法，去获取当前玩家属于哪个版本，默认版本是 app.config.php 的 PHP_VER 参数
            'PHP_VER' => $appConfig['PHP_VER'],
            'TIME_OFFSET' => SzParam::getReqParam('timeOffset'),
            'IS_COMPRESS' => $appConfig['API_COMPRESS'],
            'IS_INSTALL' => $IS_INSTALL,
            'IS_INIT_PLATFORM' => is_null($isInitPlatform) ? 0 : $isInitPlatform,
            'VERSION' => $appConfig['VERSION'],
        ));
    }
}
